/* eslint-disable no-case-declarations */
import React, { useState, useEffect } from 'react'
import { Button, Modal, Input, Spin, QRCode, App, Popover } from 'antd'
import { LinkOutlined } from '@ant-design/icons'
import { copyLink } from '@/utils/utils'
import { useModel } from '@umijs/max'
import './index.less'

/**
 * userParams
 *  channel : mp-alipay // 推广渠道
 *  page_type: 'activity'  // 首页 home 分类 category 商品详情页 goodsDetail 个人中心 my
 *  pageParams : {} // 页面参数
 */

const PromotionLinkModal = ({ isModalOpen, setIsModalOpen, userParams }) => {
  const { page_type, channel, pageParams, startParams = {} } = userParams

  const [loading, setLoading] = useState(false)

  const { platformInfo } = useModel('Global')
  const { WxGenerateScheme } = useModel('Order')
  const { GetWxQrCode } = useModel('H5Promotion')

  const [currentLinkData, setCurrentLinkData] = useState({})

  const [currentQrCode, setCurrentQrCode] = useState('') // 当前二维码

  const { message } = App.useApp()

  useEffect(() => {
    if (isModalOpen) {
      getPromotionLink()
    }
  }, [isModalOpen])

  // 获取推广链接
  const getPromotionLink = async () => {
    setLoading(true)

    // page_type 页面类型
    // channel 推广渠道

    let pageMap = {
      home: {
        // 首页
        page: 'pages/index/index',
        startParams,
        pageParams
      },
      category: {
        // 分类
        page: 'pages/category/category',
        startParams,
        pageParams
      },
      goodsDetail: {
        // 商品详情页
        page: 'pages/index/goodsDetails/goodsDetails',
        startParams,
        pageParams
      },
      my: {
        // 个人中心
        page: 'pages/my/my',
        startParams,
        pageParams
      }
    }

    // 微信链接
    let wechatLink = ''

    // 支付宝链接
    let alipayLink = ''

    // 支付宝外部链接
    let alipayPublicLink = ''

    // 支付宝灯火链接
    let lightsLink = ''

    // 支付宝灯火参数
    let lightsParams = ''

    // h5 链接
    let h5Link = ''

    // 微信小程序二维码
    let wechatQrCode = ''

    const alipayULink = 'https://ulink.alipay.com/?scheme='
    const alipayBase = 'alipays://platformapi/startapp?appId='

    switch (channel) {
      case 'mp-alipay':
        const params = generateParams(pageMap[page_type].pageParams)
        const query = generateParams(pageMap[page_type].startParams)

        const basePage = `${alipayBase}${platformInfo.ali_appid}&page=${pageMap[page_type].page}`

        // 支付宝小程序链接
        const tempPageParams = encodeURIComponent(params ? '?' + params : '')
        const tempQuery = query ? '&query=' + encodeURIComponent(query) : ''
        alipayLink = `${basePage}${tempPageParams}${tempQuery}`

        // 支付宝外部链接
        // const tempPublicPageParams = params ? encodeURIComponent('?' + encodeURIComponent(params)) : ''
        // const tempPublicQuery = query ? encodeURIComponent('&query=' + encodeURIComponent(query)) : ''
        // alipayPublicLink = `${alipayULink}${encodeURIComponent(
        //   `${basePage}${tempPublicPageParams}${tempPublicQuery}`
        // )}\r\n请复制链接到浏览器打开`

        alipayPublicLink = `${alipayULink}${encodeURIComponent(alipayLink)}\r\n请复制链接到浏览器打开`

        // 支付宝灯火链接
        lightsLink = `page=${pageMap[page_type].page}`
        lightsParams = `?${params}`

        break
      case 'mp-weixin':
        // 微信跳转链接
        const data = await generateWXLink(
          pageMap[page_type].page,
          pageMap[page_type].pageParams,
          pageMap[page_type].startParams
        )

        wechatLink = data.link
        wechatQrCode = data.qrCode

        break

      case 'h5':
        const h5startQuery = generateParams(pageMap[page_type].startParams)
        const h5pageQuery = generateParams(pageMap[page_type].pageParams)

        const h5Query = h5startQuery ? `?${h5startQuery}${h5pageQuery ? '&' + h5pageQuery : ''}` : `?${h5pageQuery}`

        let h5Url = ''
        if (platformInfo.h5_url && platformInfo.h5_url[platformInfo.h5_url.length - 1] === '/') {
          h5Url = platformInfo.h5_url.slice(0, -1)
        } else {
          h5Url = platformInfo.h5_url
        }

        if (!h5Url) {
          message.error('请联系管理员配置H5链接')
          return
        }

        h5Link = `${h5Url}/${pageMap[page_type].page}${h5Query}`

        break
    }

    setCurrentLinkData({
      wechatLink,
      alipayLink,
      alipayPublicLink,
      h5Link,
      lightsLink,
      lightsParams,
      wechatQrCode
    })
    setLoading(false)
  }

  // 参数生成
  const generateParams = params => {
    let str = ''
    // eslint-disable-next-line guard-for-in
    for (let key in params) {
      str += `${key}=${params[key]}&`
    }
    // 去掉最后一个 &
    if (str) {
      str = str.substring(0, str.length - 1)
    }
    return str
  }

  // 生成微信跳转链接
  const generateWXLink = async (path, pageParams, startParams) => {
    const startQuery = generateParams(startParams)
    const pageQuery = generateParams(pageParams)
    const query = startQuery ? `${startQuery}${pageQuery ? '&' + pageQuery : ''}` : `${pageQuery}`

    const link = await WxGenerateScheme({
      path,
      query
    })

    const qrCode = await GetWxQrCode({
      page: path,
      scene: query
    })

    if (link && qrCode) {
      return {
        link,
        qrCode
      }
    }
  }

  // 复制链接
  const handleCopyLink = link => {
    copyLink(link)
  }

  // 预览生成二维码
  const handleGenerateQRcode = () => {
    switch (channel) {
      case 'mp-alipay':
        setCurrentQrCode(currentLinkData.alipayLink)
        downloadImg(currentLinkData.alipayLink, '支付宝小程序二维码.png')
        break
      case 'mp-weixin':
        downloadImg(currentLinkData.wechatQrCode, '微信小程序二维码.png', 'wechat')
        break
      case 'h5':
        setCurrentQrCode(currentLinkData.h5Link)
        downloadImg(currentLinkData.h5Link, 'H5链接二维码.png')
        break
    }
  }

  // 下载图片
  const downloadImg = (link, picName, type) => {
    if (type === 'wechat') {
      let image = new Image()
      image.setAttribute('crossOrigin', 'anonymous')
      const width = 800
      const height = 800
      image.onload = function () {
        let canvas = document.createElement('canvas')
        canvas.width = width
        canvas.height = height
        let context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, width, height)
        let url = canvas.toDataURL('image/png')
        let a = document.createElement('a')
        let event = new MouseEvent('click')
        a.href = url
        a.download = picName || 'default.png'
        a.dispatchEvent(event)
      }
      image.src = link
    } else {
      const canvas = document.getElementById('qrcode')?.querySelector('canvas')
      if (!canvas) {
        message.error('生成二维码失败')
        return
      }
      const url = canvas.toDataURL()
      const a = document.createElement('a')
      a.download = picName || 'default.png'
      a.href = url
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      message.success('下载成功')
    }
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const LinkInput = ({ label, link }) => {
    return (
      <div className='link_input'>
        <div className='link_input_label'>{label}</div>
        <Input
          style={{ marginBottom: '10px' }}
          disabled
          value={link}
          suffix={
            <Button
              onClick={() => handleCopyLink(link)}
              style={{ color: '#3E79FE' }}
              type='text'
              icon={<LinkOutlined />}
            >
              复制链接
            </Button>
          }
        />
      </div>
    )
  }

  return (
    <Modal title='推广' open={isModalOpen} onCancel={handleCancel} footer={false} destroyOnClose={true}>
      <Spin spinning={loading} tip='生成中...'>
        <div>
          <div>
            <h3>素材下载</h3>

            <Button type='primary' ghost onClick={handleGenerateQRcode}>
              下载二维码
            </Button>

            {currentQrCode && (
              <div
                id='qrcode'
                style={{
                  position: 'absolute',
                  top: '-9999px',
                  left: '-9999px'
                }}
              >
                <QRCode size={800} level='H' value={currentQrCode} />
              </div>
            )}
          </div>
          <div>
            <h3>链接</h3>
            {channel === 'mp-alipay' && <LinkInput label='支付宝小程序链接' link={currentLinkData.alipayLink} />}
            {channel === 'mp-alipay' && <LinkInput label='支付宝外部链接' link={currentLinkData.alipayPublicLink} />}
            {channel === 'mp-alipay' && <LinkInput label='灯火链接' link={currentLinkData.lightsLink} />}
            {channel === 'mp-alipay' && <LinkInput label='灯火参数' link={currentLinkData.lightsParams} />}
            {channel === 'mp-weixin' && <LinkInput label='微信小程序链接' link={currentLinkData.wechatLink} />}
            {channel === 'h5' && <LinkInput label='H5链接' link={currentLinkData.h5Link} />}
          </div>
        </div>
      </Spin>
    </Modal>
  )
}
export default PromotionLinkModal
